import pandas as pd
import numpy as np

# Create a random dataset of 10 rows and 4 columns
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
# Randomly set some values as null
df = df.mask(np.random.random((10, 4)) < .15)
# Duplicate two cells with same values
df['B'][8] = df['B'][9]
print(df)

# --- SimpleImputer with Mean ---
from sklearn.impute import SimpleImputer
mean_imputer = SimpleImputer(strategy='mean')
result_of_mean_imputer = mean_imputer.fit_transform(df)
print(type(result_of_mean_imputer))
# transform 后生成了一个新的 numpy 数组
# transform 后丢失了column name，从新设置列名
df_of_mean_imputing = pd.DataFrame(result_of_mean_imputer, columns=list('ABCD'))
print(df_of_mean_imputing)

# --- SimpleImputer with Median ---
median_imputer = SimpleImputer(strategy='median')
result_of_median_imputer = median_imputer.fit_transform(df)
df_of_median_imputing = pd.DataFrame(result_of_median_imputer, columns=list('ABCD'))
print(df_of_median_imputing)

# --- SimpleImputer with Most Frequent ---
# If there is no most frequently occurring number
# Sklearn SimpleImputer will impute with the lowest integer on the column.
most_frequent_imputer = SimpleImputer(strategy='most_frequent')
result_most_frequent_imputing = most_frequent_imputer.fit_transform(df)
df_of_most_frequent_imputing = pd.DataFrame(result_most_frequent_imputing, columns=list('ABCD'))
print(df_of_most_frequent_imputing)


# --- SimpleImputer with Constant ---
# We first create an instance of SimpleImputer with strategy as ‘constant’ and fill_value as 99.
# If we don’t supply fill_value it will take 0 as default for numerical columns.
# Also in a numeric column, SimpleImputer does not accept a string for default fill.
constant_imputer = SimpleImputer(strategy='constant', fill_value=99)
result_constant_imputing = constant_imputer.fit_transform(df)
df_of_constant_imputing = pd.DataFrame(result_constant_imputing, columns=list('ABCD'))
print(df_of_constant_imputing)

